package com.weilai.controller;

import com.github.pagehelper.PageInfo;
import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.*;
import com.weilai.service.*;
import com.weilai.service.serviceImpl.FollowersServiceImpl;
import com.weilai.service.serviceImpl.LikesServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping
@Api(tags = "粉丝-关注", description = "用来提供粉丝与关注关系功能的接口")
public class FollowersController {
    @Autowired
    private FollowersServiceImpl followersService;
    @Autowired
    private UserService userService;
    @Autowired
    private PostsService postsService;
    @Autowired
    private LikesServiceImpl likesService;
    @Autowired
    private BackgroundService backgroundService;
    @Autowired
    private VideosService videosService;
    @Autowired
    private ThoughtService thoughtService;


    // 2.3查询粉丝列表
    @ApiOperation(value = "查询粉丝列表")
    @GetMapping("/fans")
    public ModelAndView selectFans(HttpServletRequest request) {
        Integer myId = (Integer) request.getSession().getAttribute("id");
        //myId为空，重定向到/login
        if (myId == null) {
            ModelAndView errorModelAndView = new ModelAndView();
            errorModelAndView.setViewName("redirect:/login");
            return errorModelAndView;
        }
        List<User> fans = followersService.selectFansById(myId);

        // 判断用户角色，决定返回的视图
        User currentUser = (User) request.getSession().getAttribute("user");
        String viewName = "personCenterArticle";
        if (currentUser != null && "admin".equals(currentUser.getRole())) {
            viewName += "Manager";
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("fans", fans);
        modelAndView.setViewName(viewName);
        return modelAndView;
    }

    // 2.3查询关注列表
    @ApiOperation(value = "查询关注列表")
    @GetMapping("/followings")
    public ModelAndView selectFollowings(HttpServletRequest request) {
        Integer myId = (Integer) request.getSession().getAttribute("userId");
        if (myId == null) {
            ModelAndView errorModelAndView = new ModelAndView();
            errorModelAndView.setViewName("redirect:/login");
            return errorModelAndView;
        }
        List<User> followings = followersService.selectFollowingsById(myId);
        for(User following:followings){
            following.setEmail("***");
            following.setPassword("***");
        }

        // 判断用户角色，决定返回的视图
        User currentUser = (User) request.getSession().getAttribute("user");
        String viewName = "personCenterArticle";

        ModelAndView mav = new ModelAndView();
        System.out.println("查看关注列表"+followings);
        mav.addObject("user",currentUser);
        mav.addObject("followings", followings);
        mav.setViewName(viewName);
        return mav;
    }

    //跳转个人主页
    @ApiOperation(value = "点击用户（粉丝或关注者）时跳转至其主页的方法")
    @GetMapping("/otherCenter")
    public ModelAndView homepage(@RequestParam("id")int fanId,HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        try {
            // 检查用户是否存在
            User user = userService.getUserById(fanId);
            Integer id=user.getId();
            if (user == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "未查询到该用户");
            }
            mav.addObject("user", user);
            mav.addObject("backgroundUrl",backgroundService.getByUserId(id).getUrl());

            // 获取文章
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("posts", posts);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //判断是否关注
            User u =(User) request.getSession().getAttribute("user");
            boolean isMyFollowing = followersService.isFollowing(u.getId(), user.getId());
            mav.addObject("isMyFollowing",isMyFollowing);
            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("otherCenterArticle");
            return mav;

        } catch (BusinessException e) {
            // 业务异常直接抛出，由全局异常处理器处理
            throw e;
        } catch (Exception e) {
            // 未知系统异常转换为SystemException
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "加载个人主页失败", e);
        }
    }

    @ApiOperation(value = "获取视频", notes = "")
    //获取视频
    @GetMapping("/otherCenterVideo")
    public ModelAndView videos(@RequestParam("id")Integer fanId) {
        ModelAndView mav = new ModelAndView();

        User user = userService.getUserById(fanId);
        Integer id=user.getId();
        // 获取视频
        List<Videos> videos;
        try {
            videos = videosService.selectByUserId(id);
            mav.addObject("user", user);
            mav.addObject("videos", videos);
            mav.addObject("videosNum", videos.size());
            mav.setViewName("otherCenterVideo");

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取视频数据失败", e);
        }
        return mav;
    }

    @ApiOperation(value = "获取想法", notes = "")
    //获取想法
    @GetMapping("/otherCenterIdea")
    public ModelAndView views(@RequestParam("id")Integer fanId) {
        ModelAndView mav = new ModelAndView();
        User user = userService.getUserById(fanId);
        Integer id=user.getId();
        // 获取想法
        List<Thought> Thoughts;
        try {
            Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("user", user);
            mav.addObject("Thoughts", Thoughts);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("otherCenterIdea");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取想法数据失败", e);
        }
        return mav;
    }

    //获取点赞的帖子...
    @ApiOperation(value = "获取点赞的帖子的方法", notes = "快捷访问点赞的帖子，会传递帖子集合、点赞帖子数量")
    @GetMapping("/otherCenterLike")
    public ModelAndView likes(@RequestParam("id")Integer fanId) {
        ModelAndView mav = new ModelAndView();
        User user = userService.getUserById(fanId);
        Integer id = user.getId();
        try {
            // 获取点赞的帖子
            List<Likes> likes = likesService.getLikesByUserId(id);
            List<Posts> likePosts = new ArrayList<>();
            for (Likes like : likes) {
                try {
                    Posts post = postsService.selectById(like.getPostId());
                    if (post != null) {
                        likePosts.add(post);
                    }
                } catch (Exception e) {
                    throw new SystemException(Code.SYSTEM_DB_ERROR, "获取点赞数据失败", e);
                }
            }
            List<User> likesUsers = new ArrayList<>();
            for (Posts likePost : likePosts) {
                User u=userService.getUserById(likePost.getUserId());
                u.setPassword("****");
                likesUsers.add(u);
            }
            mav.addObject("user", user);
            mav.addObject("likesUsers", likesUsers);
            mav.addObject("likePosts", likePosts);
            mav.addObject("likesNum", likePosts.size());

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("otherCenterLike");
        } catch (Exception e) {
            throw new SystemException(
                    Code.SYSTEM_DB_ERROR,
                    "获取点赞帖子失败",
                    e
            );
        }
        return mav;
    }

    @ApiOperation(value = "获取关注者的方法", notes = "快捷访问关注者")
    //关注
    @GetMapping("/otherCenterFollower")
    public ModelAndView follower(@RequestParam("id")Integer fanId) {
        ModelAndView mav = new ModelAndView();
        User user = userService.getUserById(fanId);
        Integer id = user.getId();
        // 获取关注
        try {
            List<User> follower = followersService.selectFollowingsById(id);
            for (User u : follower) {
                u.setPassword("****");
            }
            mav.addObject("user", user);
            mav.addObject("follower", follower);
            mav.addObject("followersNum", follower.size());
            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            mav.setViewName("otherCenterFollower");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取关注数据失败", e);
        }
        return mav;
    }

    @ApiOperation(value = "获取粉丝的方法", notes = "快捷访问粉丝")
    //粉丝
    @GetMapping("/otherCenterFans")
    public ModelAndView fans(@RequestParam("id")Integer fanId) {
        ModelAndView mav = new ModelAndView();
        User user = userService.getUserById(fanId);
        Integer id = user.getId();
        // 获取粉丝
        try {
            List<User> fans = followersService.selectFansById(id);
            int[] followEachOther = new int[fans.size()];
            int i=0;
            for (User u : fans) {
                u.setPassword("****");
                if(followersService.isFollowing(id, u.getId())){
                    followEachOther[i]=1;
                }
                else{
                    followEachOther[i]=0;
                }
                i++;
            }
            mav.addObject("user", user);
            mav.addObject("fans", fans);
            mav.addObject("fansNum", fans.size());
            mav.addObject("followEachOther",followEachOther);

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("otherCenterFans");

        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取关注数据失败", e);
        }
        return mav;
    }





    @ApiOperation(value = "关注他人")
    @GetMapping("/followOthers")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> followOthers(
            @RequestParam("id") Integer followingId,
            HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        try {
            // 参数校验
            if (followingId == null) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "被关注用户ID不能为空");
            }

            // 权限校验
            Integer followerId = (Integer) request.getSession().getAttribute("userId");
            if (followerId == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }

            // 执行关注操作

            followersService.followOthers(followerId, followingId);

            // 构建成功响应
            response.put("success", true);
            response.put("message", "关注成功");
            return ResponseEntity.ok(response);

        } catch (BusinessException e) {
            // 业务异常处理
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("errorMessage", e.getErrorMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            // 系统异常处理
            e.printStackTrace();
            response.put("success", false);
            response.put("errorCode", Code.SYSTEM_DB_ERROR);
            response.put("errorMessage", "关注失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @ApiOperation(value = "取消关注")
    @PostMapping("/cancelFollow")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> cancelFollow(
            @RequestParam("id") Integer followingId,
            HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        try {
            // 参数校验
            if (followingId == null) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "关注ID不能为空");
            }

            // 权限校验
            Integer followerId = (Integer) request.getSession().getAttribute("userId");
            if (followerId == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }

            // 执行取消关注
            followersService.cancelFollow(followerId, followingId);

            // 构建成功响应
            response.put("success", true);
            response.put("message", "取消关注成功");
            return ResponseEntity.ok(response);

        } catch (BusinessException e) {
            // 业务异常处理
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("errorMessage", e.getErrorMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            // 系统异常处理
            response.put("success", false);
            response.put("errorCode", Code.SYSTEM_DB_ERROR);
            response.put("errorMessage", "取消关注失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @ApiOperation(value = "显示我关注的人发布的帖子")
    @GetMapping("/mainPageAttention")
    public ModelAndView postsFromMyFollowings(HttpServletRequest request,
                                              @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                              @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        User u = (User) request.getSession().getAttribute("user");
        ModelAndView mav = new ModelAndView();

        // 使用分页查询
        try {
            PageInfo<Posts> pageInfo = followersService.postsFromMyFollowingsWithPaging(u.getId(), pageNum, pageSize);

        List<Posts> allPosts = pageInfo.getList();
        List<User> allUsers = new ArrayList<>();

        // 处理帖子和用户信息
        for (Posts post : allPosts) {
            int userId = post.getUserId();
            User user = userService.getUserById(userId);
            user.setPassword("***");
            user.setEmail("***");
            allUsers.add(user);

            // 判断是否被点赞过
            //int i = likesServiceImpl.countUserLiked(u.getId(), post.getId());
            int i = postsService.isLike(post.getId(),u.getId());
            post.setIsLiked(i == 1 ? 1 : 0);
        }

        if (allUsers.isEmpty() || allPosts.isEmpty()) {
            mav.addObject("info", "暂无关注信息");
        }

        // 添加分页信息
        mav.addObject("user", u);
        mav.addObject("allUsers", allUsers);
        mav.addObject("allPosts", allPosts);
        mav.addObject("pageInfo", pageInfo); // 分页信息

        }catch (Exception ex){
            throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND,"尚无关注信息");
        }
        // 判断用户角色，决定返回的视图
        String viewName = "mainPageAttention";
        if (u != null && "admin".equals(u.getRole())) {
            viewName += "Manager";
        }

        mav.setViewName(viewName);
        return mav;
    }

    @ApiOperation(value = "显示更多我关注的人发布的帖子")
    @GetMapping("/mainPageAttention/more")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> morePostsFromMyFollowings(
            HttpServletRequest request,
            @RequestParam(value = "pageNum", defaultValue = "2") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {

        User u = (User) request.getSession().getAttribute("user");
        Map<String, Object> response = new HashMap<>();

        try {
            // 使用分页查询
            PageInfo<Posts> pageInfo = followersService.postsFromMyFollowingsWithPaging(u.getId(), pageNum, pageSize);
            List<Posts> allPosts = pageInfo.getList();

            List<User> allUsers = new ArrayList<>();

            // 处理帖子和用户信息
            for (Posts post : allPosts) {
                int userId = post.getUserId();
                User user = userService.getUserById(userId);
                user.setPassword("***");
                user.setEmail("***");
                allUsers.add(user);

                // 判断是否被点赞过
                int i = postsService.isLike(post.getId(),u.getId());
                //int i = likesServiceImpl.countUserLiked(u.getId(), post.getId());
                post.setIsLiked(i == 1 ? 1 : 0);
            }

            response.put("user", u);
            response.put("allPosts", allPosts);
            response.put("allUsers", allUsers);
            response.put("pageInfo", pageInfo);


            response.put("success", true);
            response.put("message", "查询成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}